# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 生产者的 QPS测试.py
# @Author: dongguangwen
# @Date  : 2025-04-12 16:02
import pika
import time

# 配置
TOTAL_MESSAGES = 10000

credentials = pika.PlainCredentials('admin', 'password')
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='192.168.1.119', virtual_host='my_vhost', credentials=credentials)
)
channel = connection.channel()

# 声明交换机和队列
channel.exchange_declare(exchange='qps_test_ex', exchange_type='direct', durable=True)
channel.queue_declare(queue='qps_test_q', durable=True)
channel.queue_bind(queue='qps_test_q', exchange='qps_test_ex', routing_key='qps_key')

channel.confirm_delivery()  # 开启确认模式   开启与不开启速度差别极大

start_time = time.time()
success = 0

for i in range(TOTAL_MESSAGES):
    msg = f"message-{i}"
    try:
        channel.basic_publish(
            exchange='qps_test_ex',
            routing_key='qps_key',
            body=msg,
            properties=pika.BasicProperties(delivery_mode=2)  # 持久化
        )
        success += 1
    except pika.exceptions.UnroutableError as e:
        print(f"[!] 消息不可路由: {msg}")
    except Exception as e:
        print(f"[!] 发送失败: {e}")

end_time = time.time()
duration = end_time - start_time

print(f"\n[✅] 成功发送消息数: {success}")
print(f"[⏱] 总耗时: {duration:.2f} 秒")
print(f"[🚀] QPS: {success / duration:.2f} 条/秒")

connection.close()

"""
[✅] 成功发送消息数: 10000
[⏱] 总耗时: 9.20 秒
[🚀] QPS: 1086.99 条/秒
"""

# 不开启确认模式
"""
[✅] 成功发送消息数: 10000
[⏱] 总耗时: 1.19 秒
[🚀] QPS: 8411.05 条/秒
"""